//
//  JiaYuanAPIHelper.m
//  OneToOne
//
//  Created by Herui on 10/31/14.
//  Copyright (c) 2014 jiayuan. All rights reserved.
//

#import "JiaYuanAPIHelper.h"
#import "NSString+MD5Addition.h"
#import "JiaYuanShareData.h"
#import "DLog.h"

#define KUseNewAPI 0

#ifdef DEBUG
    #define KLogUrl  1
    #define KTestSignnature 0
#else
    #define KLogUrl 0
    #define KTestSignnature 0
#endif

@implementation JiaYuanAPIHelper
{
}

+ (NSString *)uid
{
    return [JiaYuanShareData sharedInstance].uid;

}

+ (NSString *)token
{
    return [JiaYuanShareData sharedInstance].token;
}

+ (NSString *)timeStamp
{
    NSDate *dateNow = [NSDate date];
    // 时间转时间戳
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[dateNow timeIntervalSince1970]];
    if (KTestSignnature) {
        return @"1421827630";
    } else {
        return timeSp;
    }
}

+ (NSString *)deviceId
{
    //return [JiaYuanShareData sharedInstance].deviceInfo.udid;
    return @"uiid";
}

+ (NSString *)deviceTpye
{
    return @"2";
}

+ (NSString *)appVersion
{
    return @"1.6.0";
}

+ (NSString *)channel
{
    return @"10086";
}


+ (NSString *)nonce
{
    NSString *string = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSString *nonce = @"";
    for (int i=0; i<10; i++) {
        NSUInteger random = arc4random() % 62;
        nonce = [nonce stringByAppendingString:[NSString stringWithFormat:@"%c", [string characterAtIndex:random]]];
    }
    // return nonce;
    if (KTestSignnature) {
        return @"HQDBhJSQx6";
        
    } else {
        return nonce;
    }
}

+ (NSString *)signAtureWithTimeStamp:(NSString *)timeStamp nonce:(NSString *)nonce
{
    
    NSString *sign = [NSString stringWithFormat:@"%@%@%@", @"jyvipbrk", timeStamp, nonce];
    NSString *md5Sign = [sign stringFromMD5];
    return md5Sign;
}

+ (NSString *)APIPara
{
    Class class = [self class];
    NSString *uid = [class uid];
    NSString *token = [class token];
    NSString *timeStamp = [class timeStamp];
    NSString *nonce = [class nonce];
    NSString *signAture = [class signAtureWithTimeStamp:timeStamp nonce:nonce];
    
    NSString *deviceType = [class deviceTpye];
    NSString *deviceId = [class deviceId];
    NSString *channel = [class channel];
    NSString *version = [class appVersion];
    
    NSString *apiString;
    if (KUseNewAPI) {
        apiString = [NSString stringWithFormat:@"uid=%@&token=%@&timestamp=%@&nonce=%@&device_type=%@&device_id=%@&channel=%@&ver=%@&signature=%@", uid, token, timeStamp, nonce, deviceType, deviceId, channel, version, signAture];
    } else {
        apiString = [NSString stringWithFormat:@"uid=%@&token=%@&timestamp=%@&nonce=%@&signature=%@", uid, token, timeStamp, nonce, signAture];
    }
    return apiString;
}

+ (NSString *)unloginAPIPara
{
    NSString *timeStamp = [[self class] timeStamp];
    NSString *nonce = [[self class] nonce];
    
    NSString *signAture = [[self class] signAtureWithTimeStamp:timeStamp nonce:nonce];
    NSString *apiString = [NSString stringWithFormat:@"timestamp=%@&nonce=%@&signature=%@", timeStamp, nonce, signAture];
    
    return apiString;
}

+ (NSString *)loginAPIPara
{
    NSString *timeStamp = [[self class] timeStamp];
    NSString *nonce = [[self class] nonce];
    NSString *apiString = [NSString stringWithFormat:@"timestamp=%@&nonce=%@&signature=%@", timeStamp, nonce, [[self class] signAtureWithTimeStamp:timeStamp nonce:nonce]];
    return apiString;
}


/**
 *  判断字符串是否参与验签
 *
 *  @param string post或者get参数中的key
 *
 *  @return 参与验签则返回YES, 否则返回NO
 */
+ (BOOL)isASignnatureString:(NSString *)string
{
    // action 不参与算法
    if ([string rangeOfString:@"action="].location == 0) {
        return NO;
    } else {
        
    }
    // p 不参与算法
    if ([string rangeOfString:@"p="].location == 0) {
        return NO;
    }
    // 服务中心city 不参与算法
    if ([string rangeOfString:@"city="].location == 0) {
        return NO;
    }
    // device_id 不参与算法
    if ([string rangeOfString:@"device_id="].location == 0) {
        return NO;
    }
    // device_type 不参与算法
    if ([string rangeOfString:@"device_type="].location == 0) {
        return NO;
    }
    // channel 不参与算法
    if ([string rangeOfString:@"channel="].location == 0) {
        return NO;
    }
    // ver 不参与算法
    if ([string rangeOfString:@"ver="].location == 0) {
        return NO;
    }
    // timestamp 不参与算法
    if ([string rangeOfString:@"timestamp="].location == 0) {
        return NO;
    }
    // nonce 不参与算法
    if ([string rangeOfString:@"nonce="].location == 0) {
        return NO;
    }
    // signature
    if ([string rangeOfString:@"signature="].location == 0) {
        return NO;
    }

    return YES;
}

+ (NSString *)APIParaWithURLString:(NSString *)string
{
    NSString *paraString = [[string componentsSeparatedByString:@"?"] objectAtIndex:1];
    NSArray *ParaArray = [paraString componentsSeparatedByString:@"&"];
    
    NSString *oldSign = [ParaArray lastObject];
    oldSign = [[oldSign componentsSeparatedByString:@"signature="] lastObject];  // 旧的验签
    NSString *holdOldSign = oldSign;
    
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    for (int i=0; i<ParaArray.count; i++) {
        NSString *string = [ParaArray objectAtIndex:i];
        // 判断是否需要验签
        if ([[self class] isASignnatureString:string]) {
            [mutableArray addObject:string];
        }
    }
    
    NSArray *newArray = [mutableArray sortedArrayUsingSelector:@selector(compare:)];

    for (NSString *string in newArray) {
        NSRange range = [string rangeOfString:@"="];
        NSString *value = [string substringFromIndex:range.location+range.length];
        value = [NSString stringWithFormat:@"%@", value];
        value = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        oldSign = [oldSign stringByAppendingString:value];
    }
    oldSign = [oldSign stringFromMD5];
    return [string stringByReplacingOccurrencesOfString:holdOldSign withString:oldSign];    
}

+ (NSString *)unloginAPIParaWithURLString:(NSString *)string
{
    NSString *paraString = [[string componentsSeparatedByString:@"?"] objectAtIndex:1];
    NSArray *ParaArray = [paraString componentsSeparatedByString:@"&"];
    
    NSString *oldSign = [ParaArray lastObject];
    oldSign = [[oldSign componentsSeparatedByString:@"signature="] lastObject];  // 旧的验签
    NSString *holdOldSign = oldSign;
    
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    for (int i=0; i<ParaArray.count-3; i++) {
        NSString *string = [ParaArray objectAtIndex:i];
        if (![[self class] isASignnatureString:string]) {
            continue;
        }
        [mutableArray addObject:string];
    }
    
    NSArray *newArray = [mutableArray sortedArrayUsingSelector:@selector(compare:)];
    
    for (NSString *string in newArray) {
        NSRange range = [string rangeOfString:@"="];
        NSString *value = [string substringFromIndex:range.location+range.length];
        value = [NSString stringWithFormat:@"%@", value];
        value = [value stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        oldSign = [oldSign stringByAppendingString:value];
    }
    // DLog(@"oldSign : %@", oldSign);
    oldSign = [oldSign stringFromMD5];
    return [string stringByReplacingOccurrencesOfString:holdOldSign withString:oldSign];
}

+ (NSString *)urlStringWithString:(NSString *)string isLogin:(BOOL)yesOrNo
{
    NSRange range = [string rangeOfString:[NSString stringWithUTF8String:"?"]];
    if (range.location != NSNotFound) {
        if (yesOrNo) {
            string = [NSString stringWithFormat:@"%@&%@", string, [self APIPara]];
        } else {
            string = [NSString stringWithFormat:@"%@&%@", string, [self unloginAPIPara]];
        }
    } else {
        if (yesOrNo) {
            string = [NSString stringWithFormat:@"%@?%@", string, [self APIPara]];
        } else {
            string = [NSString stringWithFormat:@"%@?%@", string, [self unloginAPIPara]];
        }
    }
    if (yesOrNo) {
        if (KLogUrl) {
            DLog(@"get url : %@", [self APIParaWithURLString:string]);
        }
        return [self APIParaWithURLString:string];
    } else {
        if (KLogUrl) {
            DLog(@"get url : %@", [self unloginAPIParaWithURLString:string]);
        }
        return [self unloginAPIParaWithURLString:string];
    }
    
    return nil;

}


+ (NSDictionary *)APIDictWithURLString:(NSString *)string dic:(NSMutableDictionary *)dic
{
    return [self APIDictWithURLString:string dic:dic isLogin:YES];
}

+ (NSDictionary *)APIDictWithURLString:(NSString *)string dic:(NSMutableDictionary *)dic isLogin:(BOOL)yesOrNo
{
    Class class = [self class];
    
    NSString *uid = [class uid];
    NSString *token = [class token];
    NSString *timeStamp = [class timeStamp];
    NSString *nonce = [class nonce];
    NSString *deviceType = [class deviceTpye];
    NSString *deviceId = [class deviceId];
    NSString *channel = [class channel];
    NSString *version = [class appVersion];
    NSString *signAture = [class signAtureWithTimeStamp:timeStamp nonce:nonce];
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionaryWithDictionary:dic];
    if (yesOrNo) {
        [paraDic setObject:uid forKey:@"uid"];
        [paraDic setObject:token forKey:@"token"];
    }
    
    [paraDic setObject:timeStamp forKey:@"timestamp"];
    [paraDic setObject:nonce forKey:@"nonce"];
    [paraDic setObject:signAture forKey:@"signature"];
    
    if (KUseNewAPI) {
        [paraDic setObject:deviceType forKey:@"device_type"];
        [paraDic setObject:deviceId forKey:@"device_id"];
        [paraDic setObject:channel forKey:@"channel"];
        [paraDic setObject:version forKey:@"ver"];
    }
   
    
    NSArray *comperArr = [[paraDic allKeys] sortedArrayUsingSelector:@selector(compare:)];
    if (KLogUrl) {
        NSRange range = [string rangeOfString:[NSString stringWithUTF8String:"?"]];
        if (range.location != NSNotFound) {
            string = [string stringByAppendingString:@"&"];
        } else {
            string = [string stringByAppendingString:@"?"];
        }
    }
    for (int i=0; i<comperArr.count; i++) {
        NSString *string = [comperArr objectAtIndex:i];
        string = [string stringByAppendingString:@"="];
        
        if (![[self class] isASignnatureString:string]) {
            continue;
        }
        NSString *strKey = [comperArr objectAtIndex:i];
        NSString *strValue = [paraDic objectForKey:strKey];
        if (KLogUrl) {
            // DLog(@"%@ | %@", strKey, strValue);
        }
        strValue = [NSString stringWithFormat:@"%@", strValue];
        strValue = [strValue stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        signAture = [signAture stringByAppendingString:strValue];
        // DLog(@"%@", signAture);
    }
    NSString *oldSign = [signAture stringFromMD5];
    // DLog(@"sign | %@", oldSign);
    [paraDic setObject:oldSign forKey:@"signature"];
    
    
    if (KLogUrl) {
        for (int i = 0; i < paraDic.allKeys.count; i++) {
            NSString *key = paraDic.allKeys[i];
            NSString *value = [paraDic objectForKey:key];
            if (i == paraDic.count-1) {
                NSString *urlPara = [NSString stringWithFormat:@"%@=%@", key, value];
                string = [string stringByAppendingString:[NSString stringWithFormat:@"%@", urlPara]];
                DLog(@"post url : %@", string);
            } else {
                NSString *urlPara = [NSString stringWithFormat:@"%@=%@", key, value];
                string = [string stringByAppendingString:[NSString stringWithFormat:@"%@&", urlPara]];
            }
        }
    }
    
    return paraDic;

}


@end
